package com.example.home.fragment

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.example.common.mvvm.BaseMvvmFragment
import com.example.entity.BaseEntity
import com.example.home.R
import com.example.home.adapter.DiscoverListAdapter
import com.example.home.databinding.FragmentDiscoverBinding
import com.example.home.databinding.ItemHomeFooterViewBinding
import com.example.home.uistate.HomeUiState
import com.example.home.viewmodel.HomeViewModel
import com.scwang.smart.refresh.header.ClassicsHeader
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class DiscoverFragment : BaseMvvmFragment<FragmentDiscoverBinding>(){

    private val mViewModel : HomeViewModel by activityViewModels()

    private  var mDiscoverAdapter : DiscoverListAdapter ? = null

    private lateinit var mFooterView :View
    private var isRefresh = false

    companion object {
        @JvmStatic
        fun newInstance() =DiscoverFragment()
    }

    override fun getLayoutId(): Int=R.layout.fragment_discover

    override fun initViews() {

        //初始化Rv
        mDataBinding.rvView.setHasFixedSize(true)//每种的item是固定大小 可以设置为true 可以减少子组件测量 提升性能
        mDataBinding.rvView.layoutManager=LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
        //初始化适配器
        mDiscoverAdapter= DiscoverListAdapter()

        //获取底部VIew并添加到适配器中
        mFooterView=DataBindingUtil.inflate<ItemHomeFooterViewBinding>(LayoutInflater.from(requireContext()),R.layout.item_home_footer_view,mDataBinding.rvView,false).root
        mDiscoverAdapter?.setFooterView(mFooterView)
        mDataBinding.rvView.adapter=mDiscoverAdapter

        //下拉刷新
        mDataBinding.refreshLayout.setRefreshHeader(ClassicsHeader(requireContext()))
        mDataBinding.refreshLayout.setOnRefreshListener {
            mViewModel.loadDiscoverData()
        }


    }

    /**
     * 懒加载数据
     * */
    override fun lazyLoadData() {
        if (mDiscoverAdapter?.data?.size==0){
            mViewModel.loadDiscoverData()
        }
    }


    override fun setDataObserver() {
        mViewModel.mLiveData.observe(this){
            when(it){
                is HomeUiState.loadDiscoverSuccess->upDataUi(it.data as List<BaseEntity>)
                is HomeUiState.loadDiscoverFail->showMsg(it.error)

                else->{}
            }
        }
    }


    private fun upDataUi(list: List<BaseEntity>){
        Log.i("====Discover", "upDataUi: ${GsonUtils.toJson(list)}")

        if (mDataBinding.refreshLayout.isRefreshing){
            mDataBinding.refreshLayout.finishRefresh()
        }

        mDiscoverAdapter?.setNewInstance(list as MutableList<BaseEntity>)

    }

}